<?php

namespace app\admin\model;

class Article extends \think\Model
{
    public function category()
    {
        return $this->belongsTo('Category', 'cid')->bind(['category_name' => 'name', 'template_list' => 'template_list', 'template_detail' => 'template_detail']);
    }

    public static function queryPage($params)
    {
        $where = [];

        if (isset($params['status'])) {
            $where[] = ['status', '=', (int) $params['status']];
        }

        if (isset($params['userid'])) {
            $where[] = ['userid', '=', (int) $params['userid']];
        }

        if (!empty($params['cid'])) {
            $where[] = ['cid', '=', (int) $params['cid']];
        }

        if (!empty($params['key'])) {
            $where[] = ['title|keywords', 'LIKE', '%' . (string)$params['key'] . '%'];
        }

        $order = ['id desc'];
        if (!empty($params['order'])) {
            if (is_array($params['order'])) {
                $order = array_unique(array_merge($params['order']));
            } else {
                array_push($order, $params['order']);
                $order = array_unique($order);
            }
        }

        $list = self::where($where)
            ->field('id,cid,title,title_pic,username,summary,clicks,sort,status,create_time')
            ->with(['category'])
            ->order($order)->paginate(['query' => $params]);

        return $list;
    }

    public static function getListByCid($cid = 0, $limit = 10, $order = "")
    {
        $where = [];

        if ($cid != 0) {
            if ($cid < 0) {
                $where[] = ['cid', '<>', abs($cid)];
            } else {
                $where[] = ['cid', '=', $cid];
            }
        }
        
        $where[] = ['status', '=', 1];

        $order = $order ?? "sort ASC,id DESC";

        return self::with('category')->where($where)
            ->field('id,cid,title,title_pic,username,summary,clicks,sort,status,create_time')
            ->order($order)->limit($limit)->select();
    }

}
